package com.example.sharesinfo.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.message.TextMessage;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bean.PersonalCenterBean;
import com.example.sharesinfo.bean.TextBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.manager.CloudManager;
import com.example.sharesinfo.model.ChatRecordModel;
import com.example.sharesinfo.utils.CommonUtils;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.gson.Gson;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class ChatRecordActivity extends BaseUIActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private static final String LOGTAG = "ChatRecordActivity:";
    private static final int GetUserSuccess = 1001;
    private static final int GetUserFailed = 1002;
    private View item_empty_view;
    private RecyclerView mChatRecordView;
    private SwipeRefreshLayout mChatRecordRefreshLayout;
    private CommonAdapter<ChatRecordModel> mChatRecordAdapter;
    private List<ChatRecordModel> mList = new ArrayList<>();
    private ImageButton ib_return;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case GetUserSuccess:
                    PersonalCenterBean result = (PersonalCenterBean) msg.obj;
                    int position = msg.arg1;
                    ChatRecordModel newRecord = mList.get(position);
                    newRecord.setNickName(result.getUsername());
                    newRecord.setUrl(result.getImageUrl());
                    mList.remove(position);
                    mList.add(position, newRecord);
                    mChatRecordAdapter.notifyDataSetChanged();
                    break;
                case GetUserFailed:

                    break;
                case 404:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_record);
        initView();
    }

    private void initView() {
        ib_return = findViewById(R.id.ib_return);
        ib_return.setOnClickListener(this);
        item_empty_view = findViewById(R.id.item_empty_view);
        mChatRecordRefreshLayout = findViewById(R.id.mChatRecordRefreshLayout);
        mChatRecordView = findViewById(R.id.mChatRecordView);
        //下拉刷新
        mChatRecordRefreshLayout.setOnRefreshListener(this);
        mChatRecordView.setLayoutManager(new LinearLayoutManager(this));
        mChatRecordView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        mChatRecordAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnBindDataListener<ChatRecordModel>() {
            @Override
            public void onBindViewHolder(final ChatRecordModel model, CommonViewHolder viewHolder, int type, final int position) {
                viewHolder.setImageUrl(ChatRecordActivity.this, R.id.iv_photo, model.getUrl());
                viewHolder.setText(R.id.tv_nickname, model.getNickName());
                viewHolder.setText(R.id.tv_content, model.getEndMsg());
                viewHolder.setText(R.id.tv_time, model.getTime());

                if (model.getUnReadSize() == 0) {
                    viewHolder.getView(R.id.tv_un_read).setVisibility(View.GONE);
                } else {
                    viewHolder.getView(R.id.tv_un_read).setVisibility(View.VISIBLE);
                    viewHolder.setText(R.id.tv_un_read, model.getUnReadSize() + "");
                }

                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ChatActivity.startActivity(ChatRecordActivity.this,
                                model.getUserId(), model.getNickName(), model.getUrl());
                    }
                });
            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.layout_chat_record_item;
            }
        });
        mChatRecordView.setAdapter(mChatRecordAdapter);
    }

    /**
     * 查询聊天记录
     */
    public void queryChatRecord() {
        if (CloudManager.getInstance().isConnect()){
            LogUtils.i("未读消息数量："+"链接成功");
        }
        mChatRecordRefreshLayout.setRefreshing(true);
        CloudManager.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                LogUtils.i("onSuccess");
                mChatRecordRefreshLayout.setRefreshing(false);
                if (CommonUtils.isEmpty(conversations)) {
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    for (int i = 0; i < conversations.size(); i++) {
                        final Conversation c = conversations.get(i);
                        String id = c.getTargetId();
                        LogUtils.i(LOGTAG + "未读：" + c.getUnreadMessageCount());
                        //查询对象的信息一会做,用户名和头像需要修改
                        ChatRecordModel chatRecordModel = new ChatRecordModel();
                        chatRecordModel.setUserId(id);
                        chatRecordModel.setUrl(SpUtils.getInstance().getString(Constants.SP_USER_IMAGE_URL, ""));
                        chatRecordModel.setNickName("用户id：" + id);
                        chatRecordModel.setTime(new SimpleDateFormat("HH:mm:ss")
                                .format(c.getReceivedTime()));
                        chatRecordModel.setUnReadSize(c.getUnreadMessageCount());
                        String objectName = c.getObjectName();
                        if (objectName.equals(CloudManager.MSG_TEXT_NAME)) {
                            TextMessage textMessage = (TextMessage) c.getLatestMessage();
                            String msg = textMessage.getContent();
                            TextBean bean = new Gson().fromJson(msg, TextBean.class);
                            if (bean.getType().equals(CloudManager.TYPE_TEXT)) {
                                chatRecordModel.setEndMsg(bean.getMsg());
                                mList.add(chatRecordModel);
                            }
                        } else if (objectName.equals(CloudManager.MSG_IMAGE_NAME)) {
                            chatRecordModel.setEndMsg("[图片]");
                            mList.add(chatRecordModel);
                        } else if (objectName.equals(CloudManager.MSG_LOCATION_NAME)) {
                            chatRecordModel.setEndMsg("[位置]");
                            mList.add(chatRecordModel);
                        }
                        queryUserInfo(id, i);
                        //mChatRecordAdapter.notifyDataSetChanged();
                        if (mList.size() > 0) {
                            item_empty_view.setVisibility(View.GONE);
                            mChatRecordView.setVisibility(View.VISIBLE);
                        } else {
                            item_empty_view.setVisibility(View.VISIBLE);
                            mChatRecordView.setVisibility(View.GONE);
                        }
                    }
                } else {
                    mChatRecordRefreshLayout.setRefreshing(false);
                    item_empty_view.setVisibility(View.VISIBLE);
                    mChatRecordView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                mChatRecordRefreshLayout.setRefreshing(false);
                item_empty_view.setVisibility(View.VISIBLE);
                mChatRecordView.setVisibility(View.GONE);
            }
        });
    }

    private void queryUserInfo(String userId, final int position) {
        String url = "http://119.23.221.142/api/user/GetHomePage?UserId=" + userId;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i(LOGTAG + s);
                PersonalCenterBean bean = new Gson().fromJson(s, PersonalCenterBean.class);
                message.what = GetUserSuccess;
                message.obj = bean;
                message.arg1 = position;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onRefresh() {
        if (mChatRecordRefreshLayout.isRefreshing()) {
            queryChatRecord();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        queryChatRecord();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_return:
                finish();
                break;
        }
    }
}
